using CfgTable;
using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.Game;
using IQIGame.Onigao.GameAOT;
using IQIGame.USDK;

namespace IQIGame.Onigao.GamePlay
{
    public class UIBuyPanel : UIBaseWindow
    {
        #region Template Generate,don't modify
        protected class UIB_UIBuyPanel
        {
            #region ObjectBinding Generate
            public IQIGame.Onigao.Framework.ExText textDesc { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btnCancel { protected set; get; }
            public IQIGame.Onigao.Framework.ExButton btnConfirm { protected set; get; }
            public UnityEngine.GameObject waitToPayNode { protected set; get; }
            public UnityEngine.GameObject selectUnit { protected set; get; }
            public UnityEngine.GameObject costMoney { protected set; get; }
            public UnityEngine.GameObject rechargeNode { protected set; get; }
            public IQIGame.Onigao.Framework.ExText textBtnBuy { protected set; get; }
            public UnityEngine.GameObject iconItem { protected set; get; }
            public UnityEngine.GameObject rawItem { protected set; get; }
            public IQIGame.Onigao.Framework.ExText textRechargeTitle { protected set; get; }
            public IQIGame.Onigao.Framework.ExText textRechargeValue { protected set; get; }
            public virtual void InitBinding(ObjectBinding __binding)
            {
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("textDesc", out var __tbv0);
                this.textDesc = __tbv0;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnCancel", out var __tbv1);
                this.btnCancel = __tbv1;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExButton>("btnConfirm", out var __tbv2);
                this.btnConfirm = __tbv2;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("waitToPayNode", out var __tbv3);
                this.waitToPayNode = __tbv3;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("selectUnit", out var __tbv4);
                this.selectUnit = __tbv4;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("costMoney", out var __tbv5);
                this.costMoney = __tbv5;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("rechargeNode", out var __tbv6);
                this.rechargeNode = __tbv6;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("textBtnBuy", out var __tbv7);
                this.textBtnBuy = __tbv7;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("iconItem", out var __tbv8);
                this.iconItem = __tbv8;
                __binding.TryGetVariableValue<UnityEngine.GameObject>("rawItem", out var __tbv9);
                this.rawItem = __tbv9;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("textRechargeTitle", out var __tbv10);
                this.textRechargeTitle = __tbv10;
                __binding.TryGetVariableValue<IQIGame.Onigao.Framework.ExText>("textRechargeValue", out var __tbv11);
                this.textRechargeValue = __tbv11;
            }
            #endregion ObjectBinding Generate 
        }
        #endregion Template Generate,don't modify

        #region Window Config
        /// <summary>
        /// 静态配置
        /// </summary>
        private static UICreateConfig _createConfig = new()
        {
            prefabName = nameof(UIBuyPanel),
            layer = EUILayer.Pop,
        };

        /// <summary>
        /// 创建UI的配置
        /// </summary>
        public override IUICreateConfig createConfig => _createConfig;
        #endregion Window Config

        #region fields
        int mallItemId = 0;
        CfgMallItem cfgMallItem = null;

        UIN_CommonSelectUnit commonSelectUnit = null;
        UIN_CostMoney costMoney = null;
        UIN_BuyIconItem singleItemInfo = null;
        UIN_BuyRawItem singleIconInfo = null;
        #endregion fields

        #region properties

        protected UIB_UIBuyPanel ui { get; private set; }
        protected UIMsgDispatcher uiMsgDispatcher => this._msgDispatcher as UIMsgDispatcher;

        #endregion properties

        protected override void BeforeInit()
        {
            ui = new UIB_UIBuyPanel();
            ui.InitBinding(this.csObjBind);
        }

        protected override void OnInit()
        {
            this.commonSelectUnit = this.InitChildNode<UIN_CommonSelectUnit>(this.ui.selectUnit);
            this.costMoney = this.InitChildNode<UIN_CostMoney>(this.ui.costMoney);
            this.singleItemInfo = this.InitChildNode<UIN_BuyIconItem>(this.ui.iconItem);
            this.singleIconInfo = this.InitChildNode<UIN_BuyRawItem>(this.ui.rawItem);
            this.ui.btnCancel.AddClickEvent(this.Close);
            this.ui.btnConfirm.AddClickEvent(this.OnBtnBuy_Clicked);

            this.HideUnit();
        }

        protected override void OnShow(UIBaseData data)
        {
            var d = data as UD_BuyPanel;
            this.InitData(d.mallItemId);
            this.ShowView();
        }

        protected override void OnHide()
        {

        }

        /// <summary>
        /// 添加UGUI侦听
        /// </summary>
        protected override void AddUGUIListener()
        {

        }

        /// <summary>
        /// 添加全局侦听（MsgDispatcher）
        /// </summary>
        protected override void AddMsgListeners()
        {
            this.uiMsgDispatcher.AddListener<int>(MsgEventType.MallItemRechargeSuccess, this.OnMsgRechargeSuccess);
        }

        protected override void OnDispose()
        {
            this.mallItemId = 0;
            this.cfgMallItem = null;
            this.commonSelectUnit = null;
            this.costMoney = null;
            this.singleItemInfo = null;
            this.singleIconInfo = null;
        }

        #region methonds

        private void HideUnit()
        {
            this.SetWaitToPayActiveSafe(false);
            this.ui.rechargeNode.SetActive(false);
            this.costMoney.Hide();
            this.singleIconInfo.Hide();
            this.singleItemInfo.Hide();
        }

        private void InitData(int mallItemCid)
        {
            this.mallItemId = mallItemCid;
            this.cfgMallItem = TableCenter.mallItem.Get(this.mallItemId);
        }

        private void SetWaitToPayActiveSafe(bool isActive)
        {
            this.ui.waitToPayNode.SetActive(isActive);
        }

        private void ShowView()
        {
            this.ui.textDesc.text = this.cfgMallItem.Desc;
            this.commonSelectUnit.Show(1, 1, this.cfgMallItem.SingleBuyLimits, this.OnNumChanged);
            this.ShowPrice(1);

            if (this.cfgMallItem.ShowItem == MallShowItemType.SingleItem)
            {
                this.singleItemInfo.Show(this.cfgMallItem.Item[0], this.cfgMallItem.ItemNum[0]);
            }
            else
            {
                this.singleIconInfo.Show(this.cfgMallItem);
            }
        }

        private void OnNumChanged(int num)
        {
            this.ShowPrice(num);
        }

        private void ShowPrice(int num)
        {
            switch (this.cfgMallItem.SellType)
            {
                case MallSellType.Item:
                case MallSellType.PayPoint:
                    this.costMoney.Show(this.cfgMallItem.Price[0], this.cfgMallItem.Price[1] * num);
                    break;
                case MallSellType.Recharge:
                    this.ui.rechargeNode.SetActive(true);
                    this.ui.textRechargeTitle.text = APIMall.RechargeTitle;
                    this.ui.textRechargeValue.text = this.cfgMallItem.Amount.ToString();
                    break;
            }
        }

        private void OnBtnBuy_Clicked()
        {
            if (this.cfgMallItem.SellType == MallSellType.Recharge)
            {
                this.SendRecharge(this.mallItemId).Forget();
            }
            else
            {
                this.SendBuy(this.mallItemId, this.commonSelectUnit.SelectNum).Forget();
            }
        }

        private async UniTaskVoid SendBuy(int mallItemCid, int num)
        {
            if (!this.costMoney.CheckIsEnough())
            {
                return;
            }

            var result = await MallModule.NetCore.CS_buy(mallItemCid, num);
            if (result.IsSuccess)
            {
                MsgDispatcher.Broadcast<int>(MsgEventType.MallItemBuySuccess, mallItemCid);
                this.Close();
                NoticeModule.ShowUIItemGet(result.getItems);
            }
        }

        private async UniTaskVoid SendRecharge(int mallItemCid)
        {
            if (!ManagerCenter.ProjectSetting.IsSDKMode())
            {
                NoticeModule.ShowNoticeNoCall(APIUIConst.NoticeCid_NoSDK);
                return;
            }

            this.SetWaitToPayActiveSafe(true);
            var payOrder = await this.CreatePayOrder(mallItemCid);
            this.PaySDK(payOrder);
            this.SetWaitToPayActiveSafe(false);
        }

        private async UniTask<LoginResponseCreateOrder> CreatePayOrder(int mallItemCid)
        {
            var orderData = new LoginRequesCreateOrderData()
            {
                serverId = GameDataCenter.CurrGameServerInfo.serverId,
                areaId = GameDataCenter.CurrGameServerInfo.areaId,
                uid = GameDataCenter.PlayerData.uid,
                pid = GameDataCenter.PlayerData.pid.ToString(),
                pname = GameDataCenter.PlayerData.playerName,
                goodsId = mallItemCid,
                extraParams = "",
            };

            var result = await new LoginWebRequest<LoginResponseCreateOrder>()
                .SendRequest(LoginMethod.CreateOrder, orderData);
            return result;
        }

        private void PaySDK(LoginResponseCreateOrder payOrder)
        {
            var payInfo = new PaymentParameters()
            {
                productId = payOrder.data.goodsId.ToString(),
                cpOrderId = payOrder.data.orderId,
                cpExtras = payOrder.data.extraParams,
            };
            IQIUSDK.Instance.pay(payInfo, SDKModule.Instance.GetRoleInfo());
        }

        private void OnMsgRechargeSuccess(int mallItemId)
        {
            if (this.mallItemId > 0 && this.mallItemId == mallItemId)
            {
                this.Close();
            }
        }

        #endregion methonds
    }
}
